package com.gdth.widget.listview.refresh;

import com.gdth.widget.listview.RefreshMode;
import com.gdth.widget.listview.listener.OnLoadListener;
import com.gdth.widget.listview.listener.OnRefreshListener;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

public class AutoListView extends ListView implements OnScrollListener{
	
	/**刷新**/
	public static final int Refresh = 0;
	/**加载**/
	public static final int LOAD = 1;

	/**区分PULL和RELEASE的距离的大小**/
	private static final int SPACE = 20;

	/**listview当前状态**/
	private RefreshMode currentState = RefreshMode.None;
	
	private HerderView mHerderView;
	private FooterView mFooterView;
	
	private RotateAnimation animation;
	private RotateAnimation reverseAnimation;

	private int startY;

	private int firstVisibleItem;
	private int scrollState;
	private int headerContentInitialHeight;
	private int headerContentHeight;

	/**只有在listview第一个item显示的时候（listview滑到了顶部）才进行下拉刷新， 否则此时的下拉只是滑动listview**/
	private boolean isRecorded;
	/**判断是否正在加载**/
	private boolean isLoading;
	/**开启或者关闭加载更多功能**/
	private boolean loadEnable = true;
	private boolean isLoadFull;
	public int pageSize = 10;

	/**下拉刷新监听**/
	private OnRefreshListener onRefreshListener;
	/**加载更多监听**/
	private OnLoadListener onLoadListener;

	public AutoListView(Context context) {
		super(context);
		
		initView();
	}

	public AutoListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		initView();
	}

	public AutoListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
		initView();
	}

	/**
	 * 初始化组件
	 * @param context
	 */
	private void initView() {
		//listview添加头部和尾部，并进行初始化
		mHerderView = new HerderView(this.getContext());
		
		headerContentInitialHeight = mHerderView.getPaddingTop();
		
		ListViewUtil.measureView(mHerderView);
		headerContentHeight = mHerderView.getMeasuredHeight();
		topPadding(-headerContentHeight);
		
		this.addHeaderView(mHerderView);
		
		//初始化底部
		mFooterView = new FooterView(this.getContext());
		this.addFooterView(mFooterView);
		
		
		initAnimation();
		
		this.setOnScrollListener(this);
	}
	
	/**
	 * 初始化箭头动画
	 */
	private void initAnimation() {
		// 设置箭头特效
		animation = new RotateAnimation(0, -180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		animation.setInterpolator(new LinearInterpolator());
		animation.setDuration(100);
		animation.setFillAfter(true);

		reverseAnimation = new RotateAnimation(-180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		reverseAnimation.setInterpolator(new LinearInterpolator());
		reverseAnimation.setDuration(100);
		reverseAnimation.setFillAfter(true);
	}

	/**
	 * 用于下拉刷新结束后的回调
	 */
	public void onRefreshComplete() {
		mHerderView.setLastUpdateTime();
		currentState = RefreshMode.None;
		refreshHeaderViewByState();
	}

	/**
	 * 用于加载更多结束后的回调
	 */
	public void onLoadComplete() {
		isLoading = false;
	}
	

	public boolean isLoadEnable() {
		return loadEnable;
	}

	/**
	 * 这里的开启或者关闭加载更多，并不支持动态调整
	 * @param loadEnable
	 */
	public void setLoadEnable(boolean loadEnable) {
		this.loadEnable = loadEnable;
		this.removeFooterView(mFooterView);
	}

	

	/**
	 * 监听触摸事件，解读手势
	 */
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (firstVisibleItem == 0) {
					isRecorded = true;
					startY = (int) ev.getY();
				}
				break;
			case MotionEvent.ACTION_UP:
				if (currentState == RefreshMode.Pull) {
					currentState = RefreshMode.None;
					refreshHeaderViewByState();
				} else if (currentState == RefreshMode.Refresh) {
					currentState = RefreshMode.Refreshing;
					refreshHeaderViewByState();
					onRefresh();
				}
				isRecorded = false;
				break;
			case MotionEvent.ACTION_MOVE:
				onMoveing(ev);
				break;

			case MotionEvent.ACTION_CANCEL:
		}
		
		return super.onTouchEvent(ev);
	}

	/**
	 * 解读手势，刷新header状态
	 * @param ev
	 */
	private void onMoveing(MotionEvent ev) {
		if (!isRecorded) {
			return;
		}
		int tmpY = (int) ev.getY();
		int space = tmpY - startY;
		int topPadding = space - headerContentHeight;
		if  (currentState == RefreshMode.None){
			if (space > 0) {
				currentState = RefreshMode.Pull;
				refreshHeaderViewByState();
			}
		}
		else if (currentState == RefreshMode.Pull){
			topPadding(topPadding);
			if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL 
					&& space > headerContentHeight + SPACE) {
				currentState = RefreshMode.Refresh;
				refreshHeaderViewByState();
			}
		}
		else if (currentState == RefreshMode.Refresh){
			topPadding(topPadding);
			if (space > 0 && space < headerContentHeight + SPACE) {
				currentState = RefreshMode.Pull;
				refreshHeaderViewByState();
			} else if (space <= 0) {
				currentState = RefreshMode.None;
				refreshHeaderViewByState();
			}
		}

	}

	/*******************************控制头、尾状态*********************************/
	/**
	 * 这个方法是根据结果的大小来决定footer显示的。
	 * 这里假定每次请求的条数为10。如果请求到了10条。则认为还有数据。如过结果不足10条，则认为数据已经全部加载，这时footer显示已经全部加载
	 * @param resultSize
	 */
	public void setResultSize(int resultSize) {
		if (resultSize == 0) {
			isLoadFull = true;
			mFooterView.setStateByFirst();
		} else if (resultSize > 0 && resultSize < pageSize) {
			isLoadFull = true;
			mFooterView.setStateByMiddle();
			
		} else if (resultSize == pageSize) {
			isLoadFull = false;
			mFooterView.setStateByLast();
		}

	}

	/**
	 *  根据当前状态，调整header
	 */
	private void refreshHeaderViewByState() {
		if (currentState == RefreshMode.None){
			topPadding(-headerContentHeight);
			mHerderView.setStateByNone();
		} else if (currentState == RefreshMode.Pull){
			mHerderView.setStateByPull(reverseAnimation);
		}else if (currentState == RefreshMode.Refresh){
			mHerderView.setStateByRefresh(animation);
		}else if (currentState == RefreshMode.Refreshing){
			topPadding(headerContentInitialHeight);
			mHerderView.setStateByRefreshing();
		}
	}

	/**
	 *  调整header的大小。其实调整的只是距离顶部的高度。
	 * @param topPadding
	 */
	private void topPadding(int topPadding) {
		mHerderView.topPadding(topPadding);
	}

	
	
	
	/**
	 * 下拉刷新监听
	 * @param onRefreshListener
	 */
	public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
		this.onRefreshListener = onRefreshListener;
	}

	/**
	 * 加载更多监听
	 * @param onLoadListener
	 */
	public void setOnLoadListener(OnLoadListener onLoadListener) {
		this.loadEnable = true;
		this.onLoadListener = onLoadListener;
	}
	
	/**
	 * 滑动手势监听
	 */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		this.scrollState = scrollState;
		ifNeedLoad(view, scrollState);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		this.firstVisibleItem = firstVisibleItem;
	}

	/**
	 * 根据listview滑动的状态判断是否需要加载更多
	 * @param view
	 * @param scrollState
	 */
	private void ifNeedLoad(AbsListView view, int scrollState) {
		if (!loadEnable) {
			return;
		}
//		try {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& !isLoading
				&& view.getLastVisiblePosition() == view.getPositionForView(mFooterView) 
				&& !isLoadFull) {
			onLoad();
			isLoading = true;
		}
//		} catch (Exception e) {
//		}
	}

	/**
	 * 刷新事件
	 */
	public void onRefresh() {
		if (onRefreshListener != null) {
			onRefreshListener.onRefresh();
		}
	}

	/**
	 * 加载事件
	 */
	public void onLoad() {
		if (onLoadListener != null) {
			onLoadListener.onLoad();
		}
	}
	
	/**
	 * 获取每次刷新加载数量
	 * @return
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * 设置每次刷新加载数量
	 * @param pageSize
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	
}
